<?php
    /*
    * @Author: KingMin 
    * @Date: 2021-07-13 22:30:33 
    * @Last Modified by:   KingMin 
    * @Last Modified time: 2021-07-13 22:30:33 
    * @The authors website: https://www.kingmin.cn  
    * 生成验证码
    *
    */
class CheckCode {
    private $font;
    public static function getstrcode(){
        $randCode = '';
        $chars = 'abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNPRSTUVWXYZ23456789';
        for ($i = 0; $i < 5; $i++) {
        	$randCode .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        $code['code']=$randCode;
        $code['sum']= strtoupper($randCode);
        return $code;
    }
    public static function getmathcode(){
        $a=mt_rand(0, 20);
        $b=mt_rand(0, 20);
        $code['code']=strtoupper($a.'+'.$b.'=?');
        $code['sum']=$a+$b;
        return $code;
    }
    public static function codeImg($randCode,$w=90,$h=30,$type='math',$mode=""){
        
        $font=PASH_ROOT.'/content/fonts/kaiti.ttf';
        $width =$w ?? 90;
        $height =$h ?? 30;
        $img = imagecreate($width, $height);
        $bgColor = isset($mode) && $mode== 't' ? imagecolorallocate($img, 245, 245, 245) : imagecolorallocate($img, 255, 255, 255);
        $pixColor = imagecolorallocate($img, mt_rand(30, 180), mt_rand(10, 100), mt_rand(40, 250));
        
        	$y = mt_rand(($h/2), ($h-2));
        for ($i = 0; $i < strlen($randCode); $i++) {
        	$x = $i * ($width/(strlen($randCode)+1)) + mt_rand(0, 10) - 2;
        	$text_color = imagecolorallocate($img, mt_rand(30, 180), mt_rand(10, 100), mt_rand(40, 250));
        // 	imagechar($img, 5, $x + 5, $y + 3, $randCode[$i], $text_color);
            if($type!='math'){
        	    $y = mt_rand(($h/2), ($h-2));
            }
            $d=mt_rand(0, 10);
            imagettftext($img, 20, $d,  $x + 5, $y + 3,$text_color,$font, $randCode[$i]);
            imagettftext($img, 20, $d,  $x + 5 + 1, $y + 3 + 1,$text_color,$font, $randCode[$i]);
        }
        for ($j = 0; $j < 80; $j++) {
        	$x = mt_rand(0, $width);
        	$y = mt_rand(0, $height);
        	imagesetpixel($img, $x, $y, $pixColor);
        }
        
        for ($j = 0; $j < 4; $j++) {
        	$x = mt_rand(0, $width);
        	$y = mt_rand(0, $height);
        	$x2 = mt_rand(0, $width);
        	$y2 = mt_rand(0, $height);
        	imageline($img, $x, $y, $x2, $y2, $pixColor);
        }
        ob_clean();
        ob_start();
        header('Content-Type: image/png');
        imagepng($img);
        imagedestroy($img);
    }
}
